#include "mainwindow1.h"
#include "addwidget.h"
#include "infodialog.h"
#include "ui_mainwindow1.h"

#include "qfrozentreewidget.h"
#include <QCalendarWidget>
#include <QComboBox>
#include <QDebug>
#include <QGraphicsDropShadowEffect>
#include <QItemDelegate>
#include <QMenu>
#include <QMessageBox>
#include <QPropertyAnimation>
#include <QScrollBar>
#include <QTime>
#include <database.hpp>

CDatabase *m_db;
TypeIndex m_type;
StatuIndex m_stat;

class ItemDelegate : public QItemDelegate
{
public:
    ItemDelegate() {}
    ~ItemDelegate() {}
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QStyleOptionViewItem viewOption(option);
        //高亮显示与普通显示时的前景色一致（即选中行和为选中时候的文字颜色一样）
        viewOption.palette.setColor(QPalette::HighlightedText, index.data(Qt::ForegroundRole).value<QColor>());
        QItemDelegate::paint(painter, viewOption, index);
    }
};

//去掉设置圆角样式后但仍存在的不透明直角
void widgetRoundInit(QWidget *w)
{
    //无直角阴影
    w->setWindowFlags(w->windowFlags() | Qt::Popup | Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint);
    //圆角背景透明
    w->setAttribute(Qt::WA_TranslucentBackground, true);
}

MainWindow1::MainWindow1(QWidget *parent)
    : QMainWindow1(parent), ui(new Ui::MainWindow1)
{
    ui->setupUi(this);

    m_db = new CDatabase();

    widgetRoundInit(ui->menuAdd);

    ui->tableWidgetTask->setFocusPolicy(Qt::NoFocus);
    ui->tableWidgetTask->setItemDelegate(new ItemDelegate); //选中不改变前景色
    tabTaskInit();
    tabDemandInit();
}

MainWindow1::~MainWindow1()
{
    delete ui;
}

//菜单栏//////////////////////////////////////////////////////////////

bool MainWindow1::AddInfo(int type)
{
    AddWidget aw(this, type);
    aw.setTitle("ADD " + m_type.toString(type));
    if (aw.exec() == QDialog::Accepted)
    {
        data_t d;
        d.tablename = TABLENAME;
        d.Statu = 0;
        d.DoneTime = 0;
        d.CreateTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss").toULongLong();
        d.Type = type;
        aw.getAttrs(d.StartTime, d.StopTime, d.ParentId);

        QStringList titles = aw.getTitles();
        for (int i = 0; i < titles.length(); i++)
        {
            d.Title = titles.at(i);
            m_db->insert(d);
        }
        return true;
    }
    return false;
}

void MainWindow1::on_actionProject_triggered()
{
    if (AddInfo(PROJECT))
        tabDemandInit();
}

void MainWindow1::on_actioneEpic_triggered()
{
    if (AddInfo(EPIC))
        tabDemandInit();
}

void MainWindow1::on_actionFeature_triggered()
{
    if (AddInfo(FEATURE))
        tabDemandInit();
}

void MainWindow1::on_actionStory_triggered()
{
    if (AddInfo(STORY))
        tabDemandInit();
}

void MainWindow1::on_actionTask_triggered()
{
    if (AddInfo(TASK))
    {
        tabTaskInit();
        tabDemandInit();
    }
}

void MainWindow1::on_actionBug_triggered()
{
    if (AddInfo(BUG))
    {
        tabTaskInit();
        tabDemandInit();
    }
}

//任务页//////////////////////////////////////////////////////////////

//双击任务表修改事件
void MainWindow1::on_tableWidgetTask_cellDoubleClicked(int row, int column)
{
    (void)column;

    InfoDialog iw(this);

    //获取双击行的数据
    data_t data;
    data.tablename = TABLENAME;
    data.Id = ui->tableWidgetTask->item(row, 0)->text().toInt();
    if (!m_db->readById(data))
        return;

    //初始化窗口显示
    iw.initWindow(data);
    if (iw.exec() != QDialog::Accepted)
        return;

    //如果选择了删除
    if (iw.ui->checkBox_del->isChecked())
    {
        if (m_db->deleteById(data))
            ui->tableWidgetTask->removeRow(row);

        return;
    }

    //检查修改
    bool show = false;
    int newstatu = iw.ui->comboBox_statu->currentIndex();
    if (newstatu == -1)
        newstatu = 0;

    if ((data.Statu == 2 && newstatu == 0) || (data.Statu == 0 && newstatu == 2))
        show = true;

    if (data.Statu != 2 && newstatu == 2)
        data.DoneTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss").toULongLong();

    if (data.Statu == 2 && newstatu != 2)
        data.DoneTime = 0;

    data.Title = iw.ui->lineEdit_title->text();
    data.Statu = newstatu;

    if (m_db->updateById(data))
    {
        if (show)
        {
            //有排序变化重新显示
            tabTaskInit();
        }
        else
        {
            ui->tableWidgetTask->item(row, 3)->setText(QString::number(data.DoneTime));
            ui->tableWidgetTask->item(row, 2)->setText(data.Title);
            ui->tableWidgetTask->item(row, 1)->setForeground(m_stat.toColor(data.Statu));
            ui->tableWidgetTask->item(row, 1)->setText(m_stat.toString(data.Statu));
        }
    }
}

//初始化显示任务表
void MainWindow1::tabTaskInit()
{
    //清除
    ui->tableWidgetTask->setRowCount(0);
    ui->tableWidgetTask->setColumnCount(0);

    //重新设置列数
    ui->tableWidgetTask->setColumnCount(4);

    //设置列表头内容
    ui->tableWidgetTask->setHorizontalHeaderLabels(QStringList() << "编号"
                                                                 << "状态"
                                                                 << "标题"
                                                                 << "时间");

    //设置列隐藏
    ui->tableWidgetTask->setColumnHidden(0, true);

    //设置列宽策略，使列自适应宽度，所有列平均分来填充空白部分
    ui->tableWidgetTask->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    ui->tableWidgetTask->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
    ui->tableWidgetTask->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch);

    ui->tableWidgetTask->horizontalHeader()->setSectionsClickable(false); //设置表头不可点击（排序）
    ui->tableWidgetTask->setSortingEnabled(true);                         //设置表头排序
    // ui->tableWidgetTask->horizontalHeader()->resizeSection(0, 150); //设置表头第一列的宽度为150
    // ui->tableWidgetTask->horizontalHeader()->setFixedHeight(40);    //设置表头的高度
    // ui->tableWidgetTask->horizontalHeader()->setDefaultSectionSize(300); //设列的宽度
    ui->tableWidgetTask->verticalHeader()->setDefaultSectionSize(40); //设置处垂直方向高度
    // ui->tableWidgetTask->setFrameShape(QFrame::NoFrame); //设置无边框
    // ui->tableWidgetTask->setShowGrid(false); //设置不显示格子线
    ui->tableWidgetTask->verticalHeader()->setVisible(false); //设置垂直头不可见，不自动显示行号
    // ui->tableWidgetTask->setSelectionMode(QAbstractItemView::NoSelection);   //设置不可选择
    ui->tableWidgetTask->setSelectionBehavior(QAbstractItemView::SelectRows);  //选择整行
    ui->tableWidgetTask->setSelectionMode(QAbstractItemView::SingleSelection); //只选择一行
    ui->tableWidgetTask->setEditTriggers(QAbstractItemView::NoEditTriggers);   //设置不可编辑

    data_t data;
    QSqlQuery query;
    query.exec(QString("SELECT * FROM %1 WHERE Type=4").arg(TABLENAME));

    int rowCount;
    QString stat;
    while (query.next())
    {
        m_db->queryToData(query, data);
        //项内容
        stat = m_stat.toString(data.Statu);

        //获取表行数，并插入新行
        rowCount = ui->tableWidgetTask->rowCount();
        ui->tableWidgetTask->insertRow(rowCount);

        //新行中创建项
        ui->tableWidgetTask->setItem(rowCount, 0, new QTableWidgetItem(QString::number(data.Id)));
        ui->tableWidgetTask->setItem(rowCount, 1, new QTableWidgetItem(stat));
        ui->tableWidgetTask->setItem(rowCount, 2, new QTableWidgetItem(data.Title));
        ui->tableWidgetTask->setItem(rowCount, 3, new QTableWidgetItem(QString::number(data.DoneTime)));

        //设置项文本颜色、对齐方式
        ui->tableWidgetTask->item(rowCount, 1)->setForeground(m_stat.toColor(data.Statu));
        ui->tableWidgetTask->item(rowCount, 1)->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

        //插入控件
        // QComboBox *cb = new QComboBox();
        // cb->addItem("未开始");
        // cb->addItem("进行中");
        // cb->addItem("已完成");
        // cb->setCurrentIndex("xxx");
        // ui->tableWidgetTask->setCellWidget(rowCount, 0, cb);
    }

    //要在添加完项后添加下面代码，先第三列降序再第一列排序
    ui->tableWidgetTask->sortItems(3, Qt::DescendingOrder);
    ui->tableWidgetTask->sortItems(1, Qt::AscendingOrder);
}

//导出页//////////////////////////////////////////////////////////////

//导出周任务标题
void MainWindow1::exportTitle(bool week)
{
    QStringList list;
    QDate start_date = QDate::currentDate();
    start_date = (week)
                     ? start_date.addDays(-start_date.dayOfWeek() + 1)
                     : start_date.addDays(-7);
    uint64_t start = start_date.toString("yyyyMMdd000000").toULongLong();
    uint64_t stop = QDateTime::currentDateTime().toString("yyyyMMddhhmmss").toULongLong();

    m_db->readTilte(start, stop, list);

    ui->textEdit_expTxt->clear();
    for (int i = 0; i < list.length(); i++)
        ui->textEdit_expTxt->append(QString::number(i + 1) + ". " + list.at(i));
}

void MainWindow1::on_pushButton_exp7day_clicked()
{
    exportTitle(false);
}

void MainWindow1::on_pushButton_expWeek_clicked()
{
    exportTitle(true);
}

void MainWindow1::on_pushButton_add_clicked()
{
    QMenu *pMenu = new QMenu(this);
    pMenu->addAction(ui->actionTask);
    pMenu->addAction(ui->actionBug);
    pMenu->addSeparator();
    pMenu->addAction(ui->actionProject);
    pMenu->addSeparator();
    pMenu->addAction(ui->actioneEpic);
    pMenu->addAction(ui->actionFeature);
    pMenu->addAction(ui->actionStory);
    QPoint p(ui->verticalGroupBox->mapToGlobal(ui->pushButton_add->pos()));
    p.setX(p.x() + ui->pushButton_add->width());
    pMenu->exec(p);
    delete pMenu;
}

//需求页//////////////////////////////////////////////////////////////

void MainWindow1::tabDemandInit()
{
    QStringList titles, ids, starttimes, stoptimes;
    QSqlQuery query;
    data_t data;

    //#项目选择框初始化
    //获取项目级别数据
    query.exec(QString("SELECT * FROM %1 WHERE Type=0").arg(TABLENAME));
    while (query.next())
    {
        m_db->queryToData(query, data);
        titles.append(data.Title);
        ids.append(QString::number(data.Id));
        stoptimes.append(QString::number(data.StopTime));
        starttimes.append(QString::number(data.StartTime));
    }

    //填充到项目选择框
    ui->comboBox_dpProId->clear();
    ui->comboBox_dpProName->clear();
    ui->comboBox_dpProStopTime->clear();
    ui->comboBox_dpProStartTime->clear();

    ui->comboBox_dpProId->addItems(ids);
    ui->comboBox_dpProName->addItems(titles);
    ui->comboBox_dpProStopTime->addItems(stoptimes);
    ui->comboBox_dpProStartTime->addItems(starttimes);

    //隐藏不重要的选择框
    ui->comboBox_dpProId->setHidden(true);
    ui->comboBox_dpProStartTime->setHidden(true);
    ui->comboBox_dpProStopTime->setHidden(true);

    //#更多操作默认隐藏
    ui->groupBox_dpMore->setHidden(true);

    //#树双击视图信号槽
    connect(ui->treeWidgetFrozen->getUpperTree(), SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(onUpperTreeItemDoubleClicked(QTreeWidgetItem *, int)));
    connect(ui->treeWidgetFrozen->getLowerTree(), SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(onLowerTreeItemDoubleClicked(QTreeWidgetItem *, int)));
}

void MainWindow1::onLowerTreeItemDoubleClicked(QTreeWidgetItem *item, int column)
{
    //获取双击项信息
    data_t data;
    data.tablename = TABLENAME;
    data.Id = item->text(1).toInt();
    if (!m_db->readById(data))
        return;

    //背景色
    QColor color = m_type.toBackgroundColor(data.Type);

    //显示时间滑块等待修改
    int newstartdate, newstopdate;
    if (ui->treeWidgetFrozen->setDateColumn(item, column, newstartdate, newstopdate))
    {
        data.StartTime = newstartdate * 1000000ull;
        data.StopTime = newstopdate * 1000000ull;
        m_db->updateById(data);
        ui->treeWidgetFrozen->changedTimes(item, newstartdate, newstopdate, color, 100);
    }
}

void MainWindow1::onUpperTreeItemDoubleClicked(QTreeWidgetItem *item, int column)
{
    (void)column;
    qDebug() << "onItemDoubleClicked";
    InfoDialog iw(this);

    data_t data;
    data.tablename = TABLENAME;
    data.Id = item->text(1).toInt();
    if (!m_db->readById(data))
        return;

    uint64_t datestart1 = data.StartTime / 1000000;
    uint64_t datestop1 = data.StopTime / 1000000;

    //设置窗口标题
    iw.initWindow(data);

    //显示窗口
    if (iw.exec() != QDialog::Accepted)
        return;

    //如果选择删除树枝
    if (iw.ui->checkBox_del->isChecked())
    {
        QStringList dels;
        data_t data;
        data.tablename = TABLENAME;

        ui->treeWidgetFrozen->getBranchText(dels, 1, item);
        for (int i = 0; i < dels.length(); i++)
        {
            data.Id = dels[i].toInt();
            m_db->deleteById(data);
        }
        ui->treeWidgetFrozen->deleteBranch(item);

        return;
    }

    //如果有添加子项
    if (iw.ui->textEdit_add_c->toPlainText().length() > 0)
    {
        data_t d;
        d.tablename = TABLENAME;
        d.Statu = 0;
        d.DoneTime = 0;
        d.CreateTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss").toULongLong();
        d.Type = data.Type + 1;
        d.StartTime = iw.ui->dateEdit_start->date().toString("yyyyMMdd000000").toULongLong();
        d.StopTime = iw.ui->dateEdit_stop->date().toString("yyyyMMdd000000").toULongLong();
        d.ParentId = data.Id;

        QStringList titles = iw.getTitles();
        for (int i = 0; i < titles.length(); i++)
        {
            d.Title = titles.at(i);
            m_db->insert(d);
            addTreeItem(item, d);
        }
    }

    //更新数据
    data.Title = iw.ui->lineEdit_title->text();
    data.Note = iw.ui->textEdit_Note->toPlainText();
    data.StartTime = iw.ui->dateEdit_start->date().toString("yyyyMMdd000000").toULongLong();
    data.StopTime = iw.ui->dateEdit_stop->date().toString("yyyyMMdd000000").toULongLong();
    if (m_db->updateById(data))
    {
        //树窗口同步显示修改
        ui->treeWidgetFrozen->changedText(item, 0, data.Title);
        ui->treeWidgetFrozen->changedText(item, 2, QString::number(iw.ui->comboBox_statu->currentIndex()));
        if (data.Type < 4 && ((data.StartTime / 1000000) != datestart1 || (data.StopTime / 1000000) != datestop1))
        {
            ui->treeWidgetFrozen->changedTimes(item, data.StartTime / 1000000, data.StopTime / 1000000, m_type.toBackgroundColor(data.Type), 100);
        }
    }
}

void MainWindow1::on_comboBox_dpProName_currentIndexChanged(const QString &arg1)
{
    if (arg1.length() == 0) // is clear
    {
        qDebug() << "on_comboBox_demandProject_currentIndexChanged clear";
        return;
    }

    qDebug() << "tree update";

    //同步隐藏信息
    int ci = ui->comboBox_dpProName->currentIndex();
    ui->comboBox_dpProId->setCurrentIndex(ci);
    ui->comboBox_dpProStartTime->setCurrentIndex(ci);
    ui->comboBox_dpProStopTime->setCurrentIndex(ci);

    //更新新树
    QColor color;
    QStringList sl;
    data_t data;
    QSqlQuery query;
    QTreeWidgetItem *parent;
    int index = ui->comboBox_dpProName->currentIndex();
    int topid = ui->comboBox_dpProId->itemText(index).toInt();
    int starttime = ui->comboBox_dpProStartTime->itemText(index).toULongLong() / 1000000;
    int stopttime = ui->comboBox_dpProStopTime->itemText(index).toULongLong() / 1000000;
    ui->treeWidgetFrozen->setColumnHeader(QStringList() << "Title"
                                                        << "Id"
                                                        << "Statu"
                                                        << "Type"
                                                        << "StartTime"
                                                        << "StopTime",
                                          6, 4, 5, 20220416, 20230101);
    ui->treeWidgetFrozen->setColumnHidden1(1, true);
    ui->treeWidgetFrozen->setColumnHidden1(3, true);

    ui->treeWidgetFrozen->setColumnHidden1(4, true);
    ui->treeWidgetFrozen->setColumnHidden1(5, true);
    query.exec(QString("SELECT * FROM %1 WHERE ParentId=%2").arg(TABLENAME).arg(topid));
    while (query.next())
    {
        m_db->queryToData(query, data);
        sl.clear();
        sl.append(data.Title);
        sl.append(QString::number(data.Id));
        sl.append(QString::number(data.Statu));
        sl.append(QString::number(data.Type));

        starttime = data.StartTime / 1000000;
        stopttime = data.StopTime / 1000000;
        sl.append(QString::number(starttime));
        sl.append(QString::number(stopttime));

        color = m_type.toBackgroundColor(data.Type);
        parent = ui->treeWidgetFrozen->createTopItem(
            sl, starttime, stopttime, color, 100);

        treeAddChid22(parent, data.Id);
    }
}

QTreeWidgetItem *MainWindow1::addTreeItem(QTreeWidgetItem *top, data_t &data)
{
    QColor color;
    QStringList sl;
    int starttime, stopttime, type;

    sl.append(data.Title);
    sl.append(QString::number(data.Id));
    sl.append(QString::number(data.Statu));
    sl.append(QString::number(data.Type));

    type = data.Type;
    //任务不需要绘制时间
    if (type > 3)
    {
        starttime = data.DoneTime / 1000000;
        stopttime = starttime;
    }
    else
    {
        starttime = data.StartTime / 1000000;
        stopttime = data.StopTime / 1000000;
    }

    sl.append(QString::number(starttime));
    sl.append(QString::number(stopttime));

    color = m_type.toBackgroundColor(type);
    QTreeWidgetItem *child = ui->treeWidgetFrozen->createChildItem(top, sl,
                                                                   starttime, stopttime, color);

    //需求页默认隐藏任务
    if (type > 3)
    {
        if (ui->checkBox_dpShowTask->isChecked())
            ui->treeWidgetFrozen->setHidden1(child, false);
        else
            ui->treeWidgetFrozen->setHidden1(child, true);
    }

    return child;
}

void MainWindow1::treeAddChid22(QTreeWidgetItem *top, int topid)
{
    QSqlQuery query1;
    QTreeWidgetItem *child;
    data_t data;
    query1.exec(QString("SELECT * FROM %1 WHERE ParentId=%2").arg(TABLENAME).arg(topid));
    while (query1.next())
    {
        m_db->queryToData(query1, data);
        child = addTreeItem(top, data);
        treeAddChid22(child, data.Id);
    }
}

void MainWindow1::on_checkBox_dpShowTask_stateChanged(int arg1)
{
    if (arg1 == Qt::Checked)
    {
        ui->treeWidgetFrozen->showAllHidden();
    }
    else
    {
        auto items = ui->treeWidgetFrozen->findItems("4", Qt::MatchContains | Qt::MatchRecursive, 3);
        for (int i = 0; i < items.length(); i++)
        {
            ui->treeWidgetFrozen->setHidden1(items[i], true);
        }
    }
}

void MainWindow1::on_checkBox_dpMore_clicked(bool checked)
{
    if (checked)
    {
        ui->groupBox_dpMore->setHidden(false);
    }
    else
    {
        ui->groupBox_dpMore->setHidden(true);
    }
}

bool MainWindow1::dp_delete(bool all)
{
    QString txt;
    QTreeWidgetItemIterator::IteratorFlags flags;
    if (all)
    {
        txt = "是否删除项目";
        flags = QTreeWidgetItemIterator::All;
    }
    else
    {
        txt = "是否删除选中行";
        flags = QTreeWidgetItemIterator::Checked;
    }

    if (QMessageBox::question(this, "确认", txt) == QMessageBox::No)
        return false;

    QStringList dels;
    data_t data;
    data.tablename = TABLENAME;

    ui->treeWidgetFrozen->getBranchTextByFlags(dels, 1, flags);
    ui->treeWidgetFrozen->deleteBranchByFlags(flags);
    for (int i = 0; i < dels.length(); i++)
    {
        data.Id = dels[i].toInt();
        m_db->deleteById(data);
    }

    return true;
}

void MainWindow1::on_pushButton_dpDeleteChecked_clicked()
{
    dp_delete(0);
}

void MainWindow1::on_pushButton_dpDeleteProject_clicked()
{
    if (!dp_delete(1))
        return;
    data_t data;
    data.tablename = TABLENAME;
    data.Id = ui->comboBox_dpProId->currentText().toInt();
    if (m_db->deleteById(data))
        ui->comboBox_dpProName->removeItem(ui->comboBox_dpProName->currentIndex());
}

void MainWindow1::on_treeWidgetFrozen_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous)
{
    (void)current;
    (void)previous;
    //    if (previous == current)
    //        return;
    //    qDebug() << "---";
    //    if (previous)
    //    {
    //        qDebug() << "previous" << previous->text(0);
    //        //        ui->treeWidgetFrozen->itemWidget(previous, 7);
    //        ui->treeWidgetFrozen->m_frontTreeWidget->removeItemWidget(
    //            ui->treeWidgetFrozen->toFrontItem(previous), 2);
    //    }
    //    if (current)
    //    {
    //        qDebug() << "current" << current->text(0);
    //        QComboBox *p = new QComboBox();
    //        p->addItem("111");
    //        p->setStyleSheet("width:2px;margin-left:90px;");
    //        ui->treeWidgetFrozen->m_frontTreeWidget->setItemWidget(
    //            ui->treeWidgetFrozen->toFrontItem(current), 2, p);
    //    }
}

void MainWindow1::on_pushButton_dpExpandAll_clicked()
{
    ui->treeWidgetFrozen->expandAll();
}

void MainWindow1::on_pushButton_dpUpExpandAll_clicked()
{
    ui->treeWidgetFrozen->collapseAll();
}

void MainWindow1::on_checkBox_dpShowTime_stateChanged(int arg1)
{
    if (arg1 == Qt::Checked)
    {
        ui->treeWidgetFrozen->setColumnHidden1(4, false);
        ui->treeWidgetFrozen->setColumnHidden1(5, false);
    }
    else
    {
        ui->treeWidgetFrozen->setColumnHidden1(4, true);
        ui->treeWidgetFrozen->setColumnHidden1(5, true);
    }
}
